package com.ruoyi.training.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.training.dto.ProjectTreeSelect;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.mapper.ProjectsMapper;
import com.ruoyi.training.domain.Projects;
import com.ruoyi.training.service.IProjectsService;

/**
 * 项目管理Service业务层处理
 *
 * @author hcc
 * @date 2025-09-16
 */
@Service
public class ProjectsServiceImpl implements IProjectsService
{
    @Autowired
    private ProjectsMapper projectsMapper;

    /**
     * 查询项目管理
     *
     * @param projectId 项目管理主键
     * @return 项目管理
     */
    @Override
    public Projects selectProjectsByProjectId(String projectId)
    {
        return projectsMapper.selectProjectsByProjectId(projectId);
    }

    /**
     * 查询项目管理列表
     *
     * @param projects 项目管理
     * @return 项目管理
     */
    @Override
    public List<Projects> selectProjectsList(Projects projects)
    {
        return projectsMapper.selectProjectsList(projects);
    }

    /**
     * 新增项目管理
     *
     * @param projects 项目管理
     * @return 结果
     */
    @Override
    public int insertProjects(Projects projects)
    {
        Projects projectsP = projectsMapper.selectProjectsByProjectId(projects.getpId());
        String[] split = projectsP.getAncestors().split(",");
        StringBuilder ancestorsName = new StringBuilder();
        for (String s : split) {
            Projects projects1 = projectsMapper.selectProjectsByProjectId(s);
            if (StringUtils.isNotNull(projects1)){
                ancestorsName.append(projects1.getProjectName()).append("/");
            }
        }
        ancestorsName.append(projects.getProjectName());
        projects.setExampleOne(ancestorsName.toString());
        if ("1".equals(projectsP.getProjectStatus()))
        {
            throw new ServiceException("上级项目已停用，不允许新增");
        }
        projects.setProjectId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
        projects.setProjectStatus("0");
        projects.setCreateTime(DateUtils.getNowDate());
        projects.setAncestors(projectsP.getAncestors() + "," + projects.getpId());
        return projectsMapper.insertProjects(projects);
    }

    /**
     * 修改项目管理
     *
     * @param projects 项目管理
     * @return 结果
     */
    @Override
    public int updateProjects(Projects projects)
    {
        Projects projectsP = projectsMapper.selectProjectsByProjectId(projects.getpId());
        String[] split = projectsP.getAncestors().split(",");
        StringBuilder ancestorsName = new StringBuilder();
        for (String s : split) {
            Projects projects1 = projectsMapper.selectProjectsByProjectId(s);
            if (StringUtils.isNotNull(projects1)){
                ancestorsName.append(projects1.getProjectName()).append("/");
            }
        }
        ancestorsName.append(projects.getProjectName());
        projects.setExampleOne(ancestorsName.toString());
        projects.setUpdateTime(DateUtils.getNowDate());
        return projectsMapper.updateProjects(projects);
    }

    /**
     * 批量删除项目管理
     *
     * @param projectIds 需要删除的项目管理主键
     * @return 结果
     */
    @Override
    public int deleteProjectsByProjectIds(String[] projectIds)
    {
        return projectsMapper.deleteProjectsByProjectIds(projectIds);
    }

    /**
     * 删除项目管理信息
     *
     * @param projectId 项目管理主键
     * @return 结果
     */
    @Override
    public int deleteProjectsByProjectId(String projectId)
    {
        return projectsMapper.deleteProjectsByProjectId(projectId);
    }
    /**
     * 逻辑删除项目管理信息
     *
     * @param projectId 项目管理主键
     * @return 结果
     */
    @Override
    public int updateFlagProjects(String projectId) {
        Projects projects = projectsMapper.selectProjectsByProjectId(projectId);
        projects.setDelFlag("1");
        projects.setUpdateTime(DateUtils.getNowDate());
        return projectsMapper.updateProjects(projects);
    }
    /**
     * 通过名称查询项目管理信息
     *
     * @param projectName 项目管理主键
     * @return 结果
     */
    @Override
    public Projects selectProjectsByProjectName(String projectName,String pId) {
        return projectsMapper.selectProjectsByProjectName(projectName,pId);
    }
    /**
     * 通过id查询项目子项目未停用数
     *
     * @param projectId 项目管理
     * @return 结果
     */
    @Override
    public int selectNormalChildrenById(String projectId) {
        return projectsMapper.selectNormalChildrenById(projectId);
    }

    /**
     * 查询项目管理树结构
     */
    @Override
    public List<ProjectTreeSelect> selectProjectsTreeList(Projects projects) {
        List<Projects> projectsList = projectsMapper.selectProjectsList(projects);
        return buildProjectTreeSelect(projectsList);
    }

    /**
     * 获取指定项目及其所有子项目的ID集合（支持多级子项目）
     * @param projectId 项目ID
     * @return 包含当前项目及所有子项目的ID集合
     * lqx
     */
    @Override
    public Set<String> getAllRelatedProjectIds(String projectId) {
        Set<String> projectIds = new HashSet<>();
        if (projectId == null || projectId.trim().isEmpty()) {
            return projectIds;
        }

        // 添加当前项目ID
        projectIds.add(projectId);

        // 递归查询所有子项目ID
        findChildProjectIds(projectId, projectIds);

        return projectIds;
    }
    /**
     * 递归查询子项目ID
     * @param parentId 父项目ID
     * @param projectIds 存储项目ID的集合
     */
    private void findChildProjectIds(String parentId, Set<String> projectIds) {
        // 查询直接子项目ID
        List<String> childIds = projectsMapper.selectChildProjectIds(parentId);

        if (childIds != null && !childIds.isEmpty()) {
            projectIds.addAll(childIds);
            // 递归查询子项目的子项目（支持多级）
            for (String childId : childIds) {
                findChildProjectIds(childId, projectIds);
            }
        }
    }

    public List<ProjectTreeSelect> buildProjectTreeSelect(List<Projects> projectsList) {
        List<Projects> projectTree = buildProjectTree(projectsList);
        return projectTree.stream().map(ProjectTreeSelect::new).collect(Collectors.toList());
    }

    private List<Projects> buildProjectTree(List<Projects> projectsList) {
        List<Projects> returnList = new ArrayList<Projects>();
        List<String> collect = projectsList.stream().map(Projects::getProjectId).collect(Collectors.toList());
        for (Projects projects : projectsList) {
            if (!collect.contains(projects.getpId())){
                recursionFn(projectsList,projects);
                returnList.add(projects);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = projectsList;
        }
        return returnList;
    }

    private void recursionFn(List<Projects> projectsList, Projects projects) {
        List<Projects> childList = getChildList(projectsList,projects);
        projects.setChildren(childList);
        for (Projects projects1 : childList)
        {
            if (hasChild(projectsList,projects1))
            {
                recursionFn(projectsList,projects1);
            }
        }
    }

    private boolean hasChild(List<Projects> projectsList, Projects projects1) {
        return getChildList(projectsList,projects1).size() > 0 ? true : false;
    }

    private List<Projects> getChildList(List<Projects> projectsList, Projects projects) {
        List<Projects> tlist = new ArrayList<>();
        Iterator<Projects> it = projectsList.iterator();
        while (it.hasNext())
        {
            Projects n = (Projects) it.next();
            if (StringUtils.isNotNull(n.getpId()) && n.getpId().equals(projects.getProjectId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

}
